package com.dingtalk.yuanhua_spring_project.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

@Service
public class DingTalkAccessimpl {
    private static final Logger logger = LoggerFactory.getLogger(DingTalkAccessimpl.class);
    private static final String GET_ACCESS_TOKEN_URL = "https://oapi.dingtalk.com/gettoken";
    @Value("${app_key}")
    private String appKey;
    @Value("${app_secret}")
    private String appSecret;

    private final AccessTokenCache accessTokenCache = new AccessTokenCache();

    public String getAccessToken() {
        if (accessTokenCache.isExpired()) {
            String url = GET_ACCESS_TOKEN_URL + "?appkey=" + appKey + "&appsecret=" + appSecret;
            try {
                String response = sendGetRequest(url);
                JSONObject json = JSONObject.parseObject(response);
                String token = json.getString("access_token");
                long timeout = json.getLong("expires_in");
                accessTokenCache.setAccessToken(token, timeout);
                return token;
            } catch (Exception e) {
                logger.error("获取 Access Token 失败", e);
                return null;
            }
        } else {
            return accessTokenCache.getAccessToken();
        }
    }

    private String sendGetRequest(String url) throws IOException {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        return readResponse(con);
    }

    // 读取响应
    private String readResponse(HttpURLConnection con) throws IOException {
        java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        return response.toString();
    }
}